package com.vitas.coin.util;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;

import com.vitas.coin.callback.IDownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {


    private static DownloadUtil downloadUtil;

    private final OkHttpClient okHttpClient;

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * 获取实例
     *
     * @return 获取实例
     */
    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    /**
     * 下载
     *
     * @param url 下载链接
     * @param listener 下载监听
     */
    public void download(final String url, String name,final IDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onFailure("1>>>"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File saveDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
                    File dstFolder = new File(saveDir,"免费铃声");
                    if (!dstFolder.exists()) {
                        dstFolder.mkdirs();
                    } else {
                        if (dstFolder.isFile()) {
                            listener.onFailure("isFile");
                            return;
                        }
                    }
                    File dstFile = new File(dstFolder,File.separator + name+".mp3");
                    if (dstFile.exists()) {
                        dstFile.delete();
                    }
                    dstFile.createNewFile();
                    fos = new FileOutputStream(dstFile);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onProgress(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDone(dstFile);
                } catch (Exception e) {
                    listener.onFailure("2>>>"+e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }


}
